package org.truenewx.tnxjee.webmvc.feign;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import org.truenewx.tnxjee.core.util.JsonUtil;
import org.truenewx.tnxjee.service.exception.ResolvableException;
import org.truenewx.tnxjee.webmvc.response.RpcResponse;

@Component
public class FeignResponseDecoder implements Decoder {

    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        Response.Body body = response.body();
        if (body != null) {
            String json = getResponseBody(response);
            RpcResponse rpcResponse = JsonUtil.json2Bean(json, RpcResponse.class);
            if (rpcResponse != null) {
                ResolvableException re = rpcResponse.toException();
                if (re != null) {
                    throw re;
                }
                return rpcResponse.getResult();
            }
        }
        return null;
    }

    private String getResponseBody(Response response) throws IOException {
        Response.Body body = response.body();
        if (body == null) {
            return "null";
        }
        return IOUtils.toString(body.asReader(StandardCharsets.UTF_8));
    }

}
